package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.client.cmn.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;

    //注入远程调用接口
    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void saveHosp(Hospital hospital) {
        if (hospital == null) {
            throw new YyghException(20001, "数据为空,添加失败!");
        }
        //save方法:有id是修改 无id是添加 先查询mongo
        Hospital targetHospital = hospitalRepository.findHospByHoscode(hospital.getHoscode());
        if (targetHospital != null) {//修改
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            //设置id 因为hospital是传过来的,永远没有id
            hospital.setId(targetHospital.getId());
            hospitalRepository.save(hospital);
        } else {//添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getHospByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.findHospByHoscode(hoscode);
        return hospital;
    }

    //医院条件查询带分页
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//更改字符串匹配规则,模糊查询
                .withIgnoreCase(true);//忽略大小写
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example example = Example.of(hospital, matcher);
        //从mongo中查询
        Page<Hospital> pageModel = hospitalRepository.findAll(example, pageable);
        //遍历数据集合,得到每个Hospital对象,远程调用,把每个Hospital对象编号对应名称取到,封装到map集合
        pageModel.getContent().stream().forEach(item -> {
            // mongo中医院集合(表)存的都是编号 需要根据编号去mysql中取出省市区
            this.packHospital(item);
        });
        return pageModel;
    }

    //根据编号获取名称进行封装到map集合
    private Hospital packHospital(Hospital hospital) {
        //封装省编号
        String provinceCode = hospital.getProvinceCode();
        String provinceString = dictFeignClient.getName(provinceCode);
        //封装市编号
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        //封装区编号
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        //封装医院编号"Hostype"
        String hostypeName = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());

        //封装到map集合
        hospital.getParam().put("hostypeString", hostypeName);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }

    @Override
    public void updateHospStatus(String id, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    //查询医院详情数据
    @Override
    public Map<String, Object> getHospById(String id) {
        //mongo中存的省市区是code  查询mysql封装省市区
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        Map<String,Object> result = new HashMap<>();
        //医院基本信息
        result.put("hospital",hospital);
        //单独处理预约规则 前端显示更直观
        result.put("bookingRule",hospital.getBookingRule());
        //不需要重复返回 即 hospital中只有基本数据 无预约规则 因为已经拿出来了
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public String getHosNameByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.findHospByHoscode(hoscode);
        String hosname = hospital.getHosname();
        return hosname;
    }

    //前端显示医院 条件查询不带分页
    @Override
    public List<Hospital> selectHospList(HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//更改字符串匹配规则,模糊查询???
                .withIgnoreCase(true);//忽略大小写

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example example = Example.of(hospital, matcher);
        //从mongo中查询 mongo中医院集合(表)存的都是编号 需要根据编号去mysql中取出省市区
        List<Hospital> list = hospitalRepository.findAll(example, sort);
        //遍历数据集合,得到每个Hospital对象,远程调用,把每个Hospital对象编号对应名称取到,封装到map集合
        list.stream().forEach(item -> {
            // mongo中医院集合(表)存的都是编号 需要根据编号去mysql中取出省市区
            this.packHospital(item);
        });
        return list;
    }

    @Override
    public List<Hospital> getHospName(String hosname) {
        List<Hospital> list = hospitalRepository.findHospByHosnameLike(hosname);
        return list;
    }

    @Override
    public Map<String, Object> getHospHoscodeApi(String hoscode) {
        Hospital hospital = this.packHospital(this.getHospByHoscode(hoscode));
        Map<String, Object> result = new HashMap<>();
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }
}